package saleMarket.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import saleMarket.domain.Customer;
import saleMarket.service.CustomerService;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 徐元坤
 * @version 1.0  12-07-2020
 */
@Slf4j
@WebServlet("/customer.ctl")
public class CustomerController extends HttpServlet {
    /**
     * {
     *     "no":"2546",
     *     "name":"张劳瑞"
     * }
     */
    /**
     * POST, http://localhost:8080/customer.ctl, 增加顾客
     * 增加一个顾客对象：将来自前端请求的JSON对象，增加到数据库表中
     * @author 201902104024@stu.sdjzu.edu.cn
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String student_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Customer对象
        Customer customerToAdd = JSON.parseObject(student_json, Customer.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加Customer对象
        try {
            if (CustomerService.getInstance().add(customerToAdd)){
                message.put("message", "增加成功");
            }else {
                message.put("message", "增加失败");
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    /**
     * http://localhost:8080/market/customer.ctl?2
     */
    /**
     * DELETE, http://localhost:8080/custmer.ctl, 删除顾客
     * 删除一个顾客对象：将来自前端请求的param，删除到数据库表中
     * @author 201902104024@stu.sdjzu.edu.cn
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Object id_obj = request.getParameter("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的Customer
            if (CustomerService.getInstance().delete(id_int)){
                respMessage_jsonObj.put("message", "删除成功");
            }else {
                respMessage_jsonObj.put("message", "删除失败");
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            System.out.println(e);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

    /**
     * {
     *     "id":1,
     *     "no":"2456",
     *     "name":"lorry",
     *     "sex":"2",
     *     "signature":"542",
     *     "phoneNumber":"2452",
     *     "address":"2452"
     * }
     */
    /**
     * PUT, http://localhost:8080/custmer.ctl, 修改顾客
     * 修改一个顾客对象：将来自前端请求的JSON对象，修改到数据库表中
     * @author 201902104024@stu.sdjzu.edu.cn
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException{
        //根据request对象，获得代表参数的JSON字串
        String customer_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Student对象
        Customer customerToUpdate = JSON.parseObject(customer_json, Customer.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改Student对象对应的记录
        try {
            if (CustomerService.getInstance().update(customerToUpdate)) {
                message.put("message", "修改成功");
            }else {
                message.put("message", "修改失败");
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    /**
     * http://localhost:8080/market/customer.ctl?2
     * http://localhost:8080/market/customer.ctl
     */
    /**
     * POST, http://localhost:8080/custmer.ctl, 查询顾客
     * 查询顾客对象：将来自前端请求的param，从数据库表中查询
     * @author 201902104024@stu.sdjzu.edu.cn
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        Object id_obj = request.getParameter("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个Student对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseCustomer(id_int, response);
            } else {
                responseCustomers(response);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            e.printStackTrace();
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
    }

    //响应一个Customer对象
    private void responseCustomer(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        Collection<Customer> customers =new ArrayList<>();
        //根据id查找Student
        Customer customer = CustomerService.getInstance().find(id);
        customers.add(customer);
        String customers_jsonStr = JSON.toJSONString(customers,
                SerializerFeature.DisableCircularReferenceDetect);

        //响应Student_json到前端
        response.getWriter().println(customers_jsonStr);
    }

    //按分页信息响应符合条件的Customer对象和对象总数
    private void responseCustomers(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //分页获得满足条件的所有Student
        Collection<Customer> customers = CustomerService.getInstance()
                .findAll();
        //第二个参数可以防止循环引用
        String customers_jsonStr = JSON.toJSONString(customers,
                SerializerFeature.DisableCircularReferenceDetect);
        //响应resp_jsonObj到前端
        response.getWriter().println(customers_jsonStr);
    }

}
